const app = getApp()
const dayjs = app.dayjs
const get_user_data = require('../../utils/get_user_data.js')
let page = 0

Page({
  data: {
    openid: app.global_data.user_data.openid,
    pages: 0,
    user_data: app.global_data.user_data,
    list: [],
    is_dark: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let openid = options.openid
    if (openid) {
      this.setData({
        openid
      })
    }
    // 检查是否登录过
    if (app.global_data.user_data.openid) {
      this.getUserData(() => {
        this.setData({
          openid:app.global_data.user_data.openid
        })
      })
    }
    this.getList(0)
    this.setData({
      user_data: app.global_data.user_data,
      is_dark: app.global_data.darkness
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    page = 0
    this.getList(page)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    page++
    this.getList(page)
  },

 /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的题库',
      path: `/pages/test_list/test_list?openid=${this.data.openid}`
    }
  },
  /* 
  朋友圈
  */
  onShareTimeline() {
    return {
      query: `openid=${this.data.openid}`
    }
  },
  ...get_user_data.methods,
  getList(page) {
    wx.cloud.callFunction({
      name: 'runDb',
      data: {
        type: 'get_list',
        collection: 'test',
        is_where: {
          "master_openid": this.data.openid,
        },
        sort: 'update_time',
        sort_category: 'desc',
        skip: page * 20,
        limit: 20
      },
      complete: res => {
        // console.log(res)
        let list = res.result.data
        // console.log(list)
        if (!list.length) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none'
          })
        }
        list.forEach(el => {
          el.update_time = dayjs(el.update_time).format('MM-DD')
        })
        this.setData({
          list: [...this.data.list, ...list]
        })
      }
    })
  },
  clickToDetail(e) {
    let {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/test_detail/test_detail?id=${id}`,
    })
  }
})